package com.starview.star.operators.relation.runtime;

import java.util.ArrayList;
import java.util.List;

import com.starview.platform.data.EvaluationException;
import com.starview.platform.data.IFunction;
import com.starview.platform.data.IRelation;
import com.starview.platform.data.IValue;
import com.starview.platform.data.type.IType;
import com.starview.platform.data.type.Refresher;
import com.starview.platform.data.type.StandardTypes;
import com.starview.platform.data.type.TypeUtils;
import com.starview.platform.data.type.TypeVar;
import com.starview.platform.data.value.Relation;
import com.starview.star.operators.CafeEnter;

public class SortRelation implements IFunction
{
  public static final String name = "__relation_sort";

  @CafeEnter
  public static IRelation enter(IRelation src, IFunction comparator) throws EvaluationException
  {
    List<IValue> tmp = new ArrayList<IValue>(src.size());
    for (IValue el : src)
      tmp.add(el);

    List<IValue> sorted = ValueSort.quickSort(tmp, comparator);
    return Relation.create(sorted);
  }

  @Override
  public IValue enter(IValue... args) throws EvaluationException
  {
    return enter((IRelation) args[0], (IFunction) args[1]);
  }

  @Override
  public IType getType()
  {
    return type();
  }

  public static IType type()
  {
    IType v = new TypeVar();
    IType comparatorType = TypeUtils.functionType(v, v, StandardTypes.booleanType);
    IType relType = TypeUtils.relationType(v);
    return Refresher.generalize(TypeUtils.functionType(relType, comparatorType, relType));
  }
}
